<script setup name="Client" lang="ts">
import { DeleteOutlined, FormOutlined, QuestionCircleOutlined } from '@ant-design/icons-vue'
import { addClient, changeStatus, delClient, getClient, listClient, updateClient } from '@/api/system/client'
import type { ClientForm, ClientQuery, ClientVO } from '@/api/system/client/types'

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'))
const { sys_grant_type } = toRefs<any>(proxy?.useDict('sys_grant_type'))
const { sys_device_type } = toRefs<any>(proxy?.useDict('sys_device_type'))
const message = useMessage()
const modal = useModal()
const queryFormRef = ref()
const clientFormRef = ref()
const clientList = ref<ClientVO[]>([])
const buttonLoading = ref(false)
const loading = ref(true)
const ids = ref<Array<string | number>>([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)

const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
})

const initFormData: ClientForm = {
  id: undefined,
  clientId: undefined,
  clientKey: undefined,
  clientSecret: undefined,
  grantTypeList: undefined,
  deviceType: undefined,
  activeTimeout: undefined,
  timeout: undefined,
  status: undefined,
}
const data = reactive<PageData<ClientForm, ClientQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    clientId: undefined,
    clientKey: undefined,
    clientSecret: undefined,
    grantType: undefined,
    deviceType: undefined,
    activeTimeout: undefined,
    timeout: undefined,
    status: undefined,
  },
  rules: {
    id: [
      { required: true, message: 'id不能为空', trigger: 'blur' },
    ],
    clientId: [
      { required: true, message: '客户端id不能为空', trigger: 'blur' },
    ],
    clientKey: [
      { required: true, message: '客户端key不能为空', trigger: 'blur' },
    ],
    clientSecret: [
      { required: true, message: '客户端秘钥不能为空', trigger: 'blur' },
    ],
    grantTypeList: [
      { required: true, message: '授权类型不能为空', trigger: 'change' },
    ],
    deviceType: [
      { required: true, message: '设备类型不能为空', trigger: 'change' },
    ],
  },
})

const { queryParams, form, rules } = toRefs(data)

/** 查询客户端管理列表 */
async function getList() {
  loading.value = true
  const res = await listClient(queryParams.value)
  clientList.value = res.rows
  total.value = res.total
  loading.value = false
}

/** 取消按钮 */
function cancel() {
  reset()
  dialog.visible = false
}

/** 表单重置 */
function reset() {
  form.value = { ...initFormData }
  clientFormRef.value?.resetFields()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection: ClientVO[]) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  dialog.visible = true
  dialog.title = '添加客户端管理'
}

/** 修改按钮操作 */
async function handleUpdate(row?: ClientVO) {
  reset()
  const _id = row?.id || ids.value[0]
  const res = await getClient(_id)
  Object.assign(form.value, res.data)
  dialog.visible = true
  dialog.title = '修改客户端管理'
}

/** 提交按钮 */
function submitForm() {
  clientFormRef.value?.validate().then(async () => {
    buttonLoading.value = true
    if (form.value.id)
      await updateClient(form.value).finally(() => buttonLoading.value = false)
    else
      await addClient(form.value).finally(() => buttonLoading.value = false)
    message.success('修改成功')
    dialog.visible = false
    await getList()
  })
}

/** 删除按钮操作 */
async function handleDelete(row?: ClientVO) {
  const _ids = row?.id || ids.value
  modal.confirm({
    title: `是否确认删除客户端管理编号为"${_ids}"的数据项？`,
    onOk: async () => {
      await delClient(_ids)
      message.success('删除成功')
      await getList()
    },
  })
}

/** 状态修改  */
async function handleStatusChange(row: ClientVO) {
  const text = row.status === '0' ? '启用' : '停用'
  try {
    modal.confirm({
      title: `确认要"${text}"吗?`,
      onOk: async () => {
        try {
          console.log('开始处理')
          await changeStatus(row.id, row.status)
          message.success(`${text}成功`)
          await getList()
        }
        catch (e) {
          console.log(e)
          row.status = row.status === '0' ? '1' : '0'
          loading.value = false
        }
      },
      onCancel: () => {
        row.status = row.status === '0' ? '1' : '0'
      },
    })
  }
  catch (err) {
    console.log(err)
  }
}

onMounted(() => {
  getList()
})
</script>

<template>
  <div class="p-2">
    <a-card class="mb-20px">
      <div class="flex-between">
        <div>
          <a-form ref="queryFormRef" class="inline-form" :model="queryParams" layout="inline">
            <a-form-item label="客户端key" prop="clientKey">
              <a-input
                v-model:value="queryParams.clientKey" placeholder="请输入客户端key" clearable style="width: 240px"
                @keyup.enter="handleQuery"
              />
            </a-form-item>
            <a-form-item label="客户端秘钥" prop="clientSecret">
              <a-input
                v-model:value="queryParams.clientSecret" placeholder="请输入客户端秘钥" clearable
                style="width: 240px"
                @keyup.enter="handleQuery"
              />
            </a-form-item>
            <a-form-item label="状态" prop="status">
              <a-select v-model:value="queryParams.status" style="width: 200px" placeholder="状态" clearable>
                <a-select-option
                  v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label"
                  :value="dict.value"
                >
                  {{ dict.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" class="mr-10px" @click="handleQuery">
                搜索
              </a-button>
              <a-button @click="resetQuery">
                重置
              </a-button>
            </a-form-item>
          </a-form>
        </div>
        <div>
          <a-row :gutter="10">
            <a-col :span="2">
              <a-button v-hasPermi="['system:client:add']" type="primary" @click="handleAdd">
                新增
              </a-button>
            </a-col>
          </a-row>
        </div>
      </div>
    </a-card>
    <a-card shadow="never">
      <a-table
        :loading="loading" :pagination="false" :data-source="clientList"
        @selection-change="handleSelectionChange"
      >
        <a-table-column title="客户端key" align="center" data-index="clientKey" />
        <a-table-column title="客户端秘钥" align="center" data-index="clientSecret" />
        <a-table-column title="授权类型" align="center">
          <template #default="{ record }">
            <dict-tag :options="sys_grant_type" :value="record.grantTypeList" />
          </template>
        </a-table-column>
        <a-table-column title="设备类型" align="center">
          <template #default="{ record }">
            <dict-tag :options="sys_device_type" :value="record.deviceType" />
          </template>
        </a-table-column>
        <a-table-column title="Token活跃超时时间" align="center" data-index="activeTimeout" />
        <a-table-column title="Token固定超时时间" align="center" data-index="timeout" />
        <a-table-column key="status" title="状态" align="center">
          <template #default="{ record }">
            <a-switch v-model:checked="record.status" checked-value="0" un-checked-value="1" @change="handleStatusChange(record)" />
          </template>
        </a-table-column>
        <a-table-column title="操作" align="center" class-name="small-padding fixed-width">
          <template #default="{ record }">
            <a-tooltip title="修改" placement="top">
              <a-button
                v-hasPermi="['system:client:edit']" type="link"
                @click="handleUpdate(record)"
              >
                <FormOutlined />
              </a-button>
            </a-tooltip>
            <a-tooltip title="删除" placement="top">
              <a-button
                v-hasPermi="['system:client:remove']" type="link"
                @click="handleDelete(record)"
              >
                <DeleteOutlined />
              </a-button>
            </a-tooltip>
          </template>
        </a-table-column>
      </a-table>
      <div class="text-right mt-5">
        <a-pagination
          v-show="total > 0"
          v-model:current="queryParams.pageNum" v-model:pageSize="queryParams.pageSize" :total="total"
          show-less-items @change="getList"
        />
      </div>
    </a-card>
    <!-- 添加或修改客户端管理对话框 -->
    <a-modal v-model:open="dialog.visible" :mask-closable="false" :keyboard="false" :title="dialog.title" width="600px" append-to-body>
      <a-form ref="clientFormRef" :model="form" :rules="rules" :label-col="{ style: 'width:150px' }">
        <a-form-item label="客户端key" prop="clientKey">
          <a-input v-model:value="form.clientKey" :disabled="form.id !== undefined" placeholder="请输入客户端key" />
        </a-form-item>
        <a-form-item label="客户端秘钥" prop="clientSecret">
          <a-input v-model:value="form.clientSecret" :disabled="form.id !== undefined" placeholder="请输入客户端秘钥" />
        </a-form-item>
        <a-form-item label="授权类型" prop="grantTypeList">
          <a-select v-model:value="form.grantTypeList" :max-tag-count="1" mode="multiple" placeholder="请输入授权类型">
            <a-select-option v-for="dict in sys_grant_type" :key="dict.value" :label="dict.label" :value="dict.value">
              {{ dict.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="设备类型" prop="deviceType">
          <a-select v-model:value="form.deviceType" placeholder="请输入设备类型">
            <a-select-option v-for="dict in sys_device_type" :key="dict.value" :label="dict.label" :value="dict.value">
              {{ dict.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item prop="activeTimeout" label-width="auto">
          <template #label>
            <span>
              <a-tooltip title="指定时间无操作则过期（单位：秒），默认30分钟（1800秒）" placement="top">
                <a-icon><QuestionCircleOutlined /></a-icon>
              </a-tooltip>
              Token活跃超时时间
            </span>
          </template>
          <a-input v-model:value="form.activeTimeout" placeholder="请输入Token活跃超时时间" />
        </a-form-item>
        <a-form-item prop="timeout" label-width="auto">
          <template #label>
            <span>
              <a-tooltip content="指定时间必定过期（单位：秒），默认七天（604800秒）" placement="top">
                <a-icon><QuestionCircleOutlined /></a-icon>
              </a-tooltip>
              Token固定超时时间
            </span>
          </template>
          <a-input v-model:value="form.timeout" placeholder="请输入Token固定超时时间" />
        </a-form-item>
        <a-form-item label="状态">
          <a-radio-group v-model:value="form.status">
            <a-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value" :label="dict.value">
              {{ dict.label }}
            </a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
      <template #footer>
        <div class="dialog-footer">
          <a-button :loading="buttonLoading" type="primary" @click="submitForm">
            确 定
          </a-button>
          <a-button @click="cancel">
            取 消
          </a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>
